<?php

class BuildingsController extends Zend_Controller_Action
{
    private $_userBuildingDetails = null;
    private $_restrictions = null;
    private $_unitsDetails = null;
    private $_currentUserStats = null;
    private $_userArmy = null;

    public function init()
    {
       $this->_userBuildingDetails = new stdClass();
       $this->_restrictions = new stdClass();
       $this->_unitsDetails = new stdClass();
       $this->_currentUserStats = new stdClass();
       $this->_userArmy = new stdClass();
    }

    public function setUserArmy($userArmy)
    {
    	$this->_userArmy = $userArmy;
    }

    public function setUserBuildingDetails($userBuildingDetails)
    {
    	$this->_userBuildingDetails = $userBuildingDetails;
    }

    public function setRestrictions($restrictions)
    {
    	$this->_restrictions = $restrictions;
    }

    public function setUnitsDetails($unitsDetails)
    {
    	$this->_unitsDetails = $unitsDetails;
    }

    public function setCurrentUserStats($userCurrentStats)
    {
    	$this->_currentUserStats = $userCurrentStats;
    }

    public function indexAction()
    {
        // action body
    }

    public function actionsAction()
    {
    	
        if( $_GET['v'] != null){
    		$buildingName = $_GET['v'];
    	}
    	
    	if ( $buildingName == null )
    	{
    		$this->_redirect('kingdom/list');
    	}
    	
    	$auth = Zend_Auth::getInstance();
       	if ($auth->hasIdentity()) 
        {
            $user_id = $auth->getIdentity()->id; 
            $unitType = $this->getUnitTypeFromBuildingName($buildingName);         
        }
        else 
        {
        	$this->_redirect('authentication/login');
        }
        
       	$this->setBuildingValues($user_id, $buildingName);
        $this->view->buildingName = $buildingName;
        $story = $this->_userBuildingDetails->buildingText;
        $this->view->buildingText = $story;
    }

    private function fixString($error)
    {
    	$error = str_replace("+", " ", $error);
	    $error = str_replace("%27", "'", $error);
	    $error = str_replace("%28", "(", $error);
	    $error = str_replace("%29", ")", $error);
	    $error = str_replace("%21", "!", $error);
	   
	    
	    return $error;
    }

    private function setBuildingValues($user_id, $buildingName)
    {
    	//get current users stats; 
	    $currentStats = $this->getCurrentUserStats($user_id);
	    $this->setCurrentUserStats($currentStats);
	    
	    //get current building details
	    $userBuildingDetails = $this->getUserBuildingDetails($buildingName, $user_id);
	    $this->setUserBuildingDetails($userBuildingDetails);
	    
	    //get unitsDetails
	    $unitsDetails = $this->getUnitsDetails($user_id);
	    $this->setUnitsDetails($unitsDetails);
	    
	    $userArmy = $this->getUserArmy($user_id,  $this->_currentUserStats->classFK);
	    $this->setUserArmy($userArmy);
	    
	    //get restrictions 
	    $restrictions = $this->getAllRestrictions($buildingName, $user_id);
	    $this->setRestrictions($restrictions);
	    
    }

    

    private function user_build($buildingName, $user_id)
    {
    	$userBuildingsTbl = new Application_Model_UserBuildingsTbl();
    	$userStats = new Application_Model_UserStatsTbl();
    	
    	
    	$this->setBuildingValues($user_id, $buildingName);
    	
    	
    	$unitType = $this->getUnitTypeFromBuildingName($buildingName);
    	$buildingUpgradeCost = $this->_userBuildingDetails->buildingUpgradeCost;
    	$unitLvl1 =  $this->getCurrentUnitSettings(1);
    	$unitLvl1Power = $unitLvl1->power;
    	$buildingLevel = $this->_userBuildingDetails->buildingLevel + 1;
    	$capacity = $this->getBuildingCapacity($buildingUpgradeCost, $unitType, $unitLvl1Power, $buildingLevel, $user_id);
    	$this->view->capacity = $capacity;
    	
    	$building_id = $this->_userBuildingDetails->buildingId;
    	
    	//1. insert into user_buildings table values
		if( $this->_userBuildingDetails->buildingLevel == 0 )
		{
        	$data = array (
	    					'user_fk' => $user_id,
	    					'building_fk' => $building_id,
	    					'building_current_lvl' => 1
	    			);		
	    	$userBuildingsTbl->insert($data);
	    }
	    else
	    {
			$row = $userBuildingsTbl->fetchRow($userBuildingsTbl->select()->where('user_fk = ?', $user_id)->where('building_fk = ?', $building_id));
			$building_lvl = $row->building_current_lvl + 1;
			$row->building_current_lvl = $building_lvl;
			//UPDATE the row in the database with new values
			$row->save();
	    }
	        
    	//2. update wealth
		$row = $userStats->fetchRow($userStats->select()->where('user_fk = ?', $user_id));
		$upgrade_cost = $this->_userBuildingDetails->buildingUpgradeCost;
		$row->wealth = $row->wealth - $upgrade_cost;
		$row->total_population = $row->total_population + $capacity;
    	$row->save();
    	return true;
    	
    }

    private function getCurrentUnitSettings($unitType)
    {
    	$unit = new stdClass();
    	switch($unitType)
    	{
    		case 1:
    			$level = 'lvl1';
    			break;
    		case 2:
    			$level = 'lvl2';
    			break;
    		case 3:
    			$level = 'lvl3';
    			break;
    		case 4:
    			$level = 'lvl4';
    			break;
    		case 5:
    			$level = 'lvl5';
    			break;
    		case 6:
    			$level = 'lvl6';
    			break;
    		default: break;
    	}
    	
    	$unit->power = $this->_unitsDetails->power[$level];
    	$unit->income = $this->_unitsDetails->income[$level];
    	$unit->cost = $this->_unitsDetails->cost[$level];
    	$unit->story = $this->_unitsDetails->story[$level];
    	$unit->name = $this->_unitsDetails->name[$level];
    	$unit->trainingCost = $this->_unitsDetails->trainingCost[$level];
    	$unit->trainingPower = $this->_unitsDetails->trainingPower[$level];
    	$unit->trainingIncome = $this->_unitsDetails->trainingIncome[$level];
    	
    	return $unit;
    }

    private function getUserArmy($user_id, $class_fk)
    {
    	$userArmy = new stdClass();
    	if( $this->_currentUserStats->classFK == 1 )
	   	{
    		$lighArmy = new Application_Model_LightUserArmyTbl();
    		$row = $lighArmy->fetchRow($lighArmy->select()->where('user_fk = ?', $user_id));
	    }
	    else 
	   	{
   			$darkArmy = new Application_Model_DarkUserArmyTbl();	
   			$row = $darkArmy->fetchRow($darkArmy->select()->where('user_fk = ?', $user_id));
	   	}
	   	$userArmy = $row;
    	return $userArmy;
    }

    private function getUnitsDetails($user_id)
    {
    	$unitsDetails = new stdClass();
    	
    	/*
	     * options:
	     * 1 - power
	     * 2 - income
	     * 3 - cost
	     * 4 - story
	     * 5 - name
	     * 6 - trainingCost
	     * 
	     */
    	
    	$unitsDetails->power = $this->getAllUnitsSettingsForRaceId($this->_currentUserStats->raceId, 1);
    	$unitsDetails->income = $this->getAllUnitsSettingsForRaceId($this->_currentUserStats->raceId, 2);
    	$unitsDetails->cost = $this->getAllUnitsSettingsForRaceId($this->_currentUserStats->raceId, 3);
    	$unitsDetails->story = $this->getAllUnitsSettingsForRaceId($this->_currentUserStats->raceId, 4);
    	$unitsDetails->name = $this->getAllUnitsSettingsForRaceId($this->_currentUserStats->raceId, 5);
    	
    	$unitsPower = $unitsDetails->power;
    	$hireCost = $unitsDetails->cost;
    	$unitIncome = $unitsDetails->income;
    	
    	$unitsDetails->trainingCost = $this->getAllUnitsTrainingCost($hireCost);
    	$unitsDetails->trainingPower = $this->getAllUnitsTrainingPower($unitsPower);
    	$unitsDetails->trainingIncome = $this->getAllUnitsTrainingIncome($unitsPower, $unitIncome);
    	return $unitsDetails;
    }

    private function getAllUnitsTrainingCost($hireCost)
    {
    	$trainingCost['lvl1'] = 0;
    	$trainingCost['lvl2'] = round($hireCost['lvl2']*1.1)- $hireCost['lvl1'];
    	$trainingCost['lvl3'] = round($hireCost['lvl3']*1.1)- $hireCost['lvl1'];
    	$trainingCost['lvl4'] = round($hireCost['lvl4']*1.1)- $hireCost['lvl1'];
    	$trainingCost['lvl5'] = round($hireCost['lvl5']*1.1)- $hireCost['lvl1'];
    	$trainingCost['lvl6'] = 0;
    	
    	return $trainingCost;
    }

    private function getAllUnitsTrainingIncome($unitsPower, $unitIncome)
    {
    	$trainingIncome['lvl1'] = $unitIncome['lvl1'];
    	$trainingIncome['lvl2'] = $unitIncome['lvl2']/$unitsPower['lvl2'] * ($unitsPower['lvl2']-$unitsPower['lvl1']);
    	$trainingIncome['lvl3'] = $unitIncome['lvl3']/$unitsPower['lvl3'] * ($unitsPower['lvl3']-$unitsPower['lvl1']);
    	$trainingIncome['lvl4'] = $unitIncome['lvl4']/$unitsPower['lvl4'] * ($unitsPower['lvl4']-$unitsPower['lvl1']);
    	$trainingIncome['lvl5'] = $unitIncome['lvl5']/$unitsPower['lvl5'] * ($unitsPower['lvl5']-$unitsPower['lvl1']);
    	$trainingIncome['lvl6'] = $unitIncome['lvl6'];
    	
    	return $trainingIncome;
    }

    private function getAllUnitsTrainingPower($unitsPower)
    {
    	$trainPower['lvl1'] = $unitsPower['lvl1'];
    	$trainPower['lvl2'] = $unitsPower['lvl2'] - $unitsPower['lvl1'];
    	$trainPower['lvl3'] = $unitsPower['lvl3'] - $unitsPower['lvl1'];
    	$trainPower['lvl4'] = $unitsPower['lvl4'] - $unitsPower['lvl1'];
    	$trainPower['lvl5'] = $unitsPower['lvl5'] - $unitsPower['lvl1'];
    	$trainPower['lvl6'] = $unitsPower['lvl6'];
    	
    	return $trainPower;
    }

    private function getAllUnitsSettingsForRaceId($race_id, $option)
    {
    	$raceUnits = new Application_Model_RaceUnits();
    	switch($option)
    	{
    		case 1: 
    			$values = $raceUnits->getUnitsPowerForRaceID($race_id);
    			break;
    		case 2: 
    			$values = $raceUnits->getUnitsIncomeForRaceID($race_id);
    			break;
    		case 3:
    			$values = $raceUnits->getUnitsCostForRaceID($race_id); 
    			break;
    		case 4:
    			$values = $raceUnits->getUnitsDescriptionForRaceID($race_id);
    			break;
    		case 5: 
    			$values = $raceUnits->getUnitsNameForRaceID($race_id);
    			break;
    		default: break;
    	}
    	return $values;
    }

    private function getAllRestrictions($currentBuildingName, $user_id)
    {
    	$restrictions = new stdClass();
    	//1. building restrictions
    	$restrictions->building->buildingRestrictionName = 0;
    	$restrictions->building->buildingRestrictionLevel = 0;
    	if( $this->_userBuildingDetails->buildingRestrictionIdentifier != null && $this->_userBuildingDetails->buildingRestrictionIdentifierLevel != null )
    	{
    		//check if building restrictionIdentifier is on requested level
    		//get buildingId and buildingName of the BuildingRestrictionIdentifier
    		$idAndName = $this->getBuildingIdAndNameFromBuildingIdentifier($this->_userBuildingDetails->buildingRestrictionIdentifier);
    		$restrictedBuildingId = $idAndName['id'];
    		$restrictedBuldingName = $idAndName['name'];
    		
    		$levelRequested = $this->getBuildingLevel($user_id, $restrictedBuildingId);
    		if($this->_userBuildingDetails->buildingRestrictionIdentifierLevel > $levelRequested )
    		{
    			$restrictions->building->buildingRestrictionName = $restrictedBuldingName;
    			$restrictions->building->buildingRestrictionLevel = $this->_userBuildingDetails->buildingRestrictionIdentifierLevel;
    		}
    		else 
    		{
    			$restrictions->building->buildingRestrictionName = 0;
    			$restrictions->building->buildingRestrictionLevel = 0;
    		}
    		
    	}
    	
    	//2.building cost restrictions
    	if ( $this->_userBuildingDetails->buildingUpgradeCost > $this->_currentUserStats->currentWealth )
    	{
    		$restrictions->building->buildingCostRestriction = $this->_userBuildingDetails->buildingUpgradeCost -  $this->_currentUserStats->currentWealth;
    	}
    	else 
    	{
    		$restrictions->building->buildingCostRestriction = 0;
    	}
    	
    	$noTrain = 0;
    	$unitType = $this->getUnitTypeFromBuildingName($currentBuildingName);
    	//2. training restrictions
    	if( $unitType == 1  || $unitType == 6 )
    	{
    		$noTrain = 1;
    		$restrictions->training->farms = "You cannot train this type of unit! You can only hire it!";
    		$restrictions->training->buildingName = 0;
    		$restrictions->training->buildingLevel = 0;	
    	}
    	else
    	{
    		if( $unitType != -1 )
    		{
	    		$restrictions->training->farms = "0";
	    		if( $this->_userBuildingDetails->buildingLevel < 1  )
	    		{
	    			$restrictions->training->buildingName = $currentBuildingName;
	    			$restrictions->training->buildingLevel = 1;
	    		}
	    		else
	    		{
	    			$restrictions->training->buildingName = 0;
	    			$restrictions->training->buildingLevel = 0;
	    		}
	    		
	    		
	    		//CHECK IF THERE IS LVL1 UNITS TO BE  TRAINED
	    		$restrictions->training->population = 0;
	    		if ($this->_userArmy->lvl1 <= 0)
	    		{
		    		$restrictions->training->population = "Buy more level 1 units";
	    		}
    		}

    	}
    		
    	
    	//3. hire restrictions
    	if( $this->_userBuildingDetails->buildingLevel < 2 && $noTrain == 0 )
    	{
    		$restrictions->hire->buildingName = $currentBuildingName;
    		$restrictions->hire->buildingLevel = 2;
    	}
    	else if (  $this->_userBuildingDetails->buildingLevel < 1 && $noTrain == 1 )
    	{
    		$restrictions->hire->buildingName = $currentBuildingName;
    		$restrictions->hire->buildingLevel = 1;
    	}
    	else 
    	{
    		$restrictions->hire->buildingName = 0;
    		$restrictions->hire->buildingLevel = 0;
    	}
    		
    	if( $this->_currentUserStats->current_population >= $this->_currentUserStats->total_population )
    		$restrictions->hire->population = "Build more farms";
    	else
    		$restrictions->hire->population = 0;
    	
    	return $restrictions;
    	
    }

    private function getCurrentUserStats($user_id)
    {
    	$userStatsDetails = new stdClass();
    	$userStatsTbl = new Application_Model_UserStatsTbl();
    	$result = $userStatsTbl->getUserStats($user_id);
    	
    	if($result != null)
    	{
    		$userStatsDetails->userFK = $result['user_fk'];
    		$userStatsDetails->power = round($result['power']);
    		$userStatsDetails->AP = $result['attack_points'];
    		$userStatsDetails->currentWealth = $result['wealth'];
    		$userStatsDetails->income = $result['income'];
    		$userStatsDetails->coinsEarn = $result['coins_earn'];
    		$userStatsDetails->coinsLost = $result['coins_lost'];
    		$userStatsDetails->heroLevel = $result['hero_level'];
    		$userStatsDetails->turnsPlayed = $result['turns_played'];
    		$userStatsDetails->current_population = $result['current_population'];
    		$userStatsDetails->total_population = $result['total_population'];
    		//get now the race and the class
    		$roundSettings = new Application_Model_RoundSettingsTbl();
    		$result = $roundSettings->getRoundSettingsByUserID($user_id);
    		//'user_fk','alias','race_fk','class_fk'
    		if( $result != null )
    		{
				$userStatsDetails->raceId = $result['race_fk']; 
				$userStatsDetails->classFK = $result['class_fk'];
    		}		
    	}
    	return $userStatsDetails;
    }

    private function getBuildingIdAndNameFromBuildingIdentifier($buildingIdentifier)
    {
    	$buildingsTbl = new Application_Model_BuildingsTbl();
    	$result = $buildingsTbl->getBuildingIdByBuildingIdentifier($buildingIdentifier);
    	//'id','building_identifier','name'
    	if ($result != null)
    		return $result;
    }

    private function getUnitTypeFromBuildingName($buildingName)
    {
    	  switch ($buildingName){
	    		case 'farms': $unitType = 1;
	    			break;
	    		case 'barracks': $unitType = 2;
	    			break;
	    		case 'archery': $unitType = 3;
	    			break;
	    		case 'stable': $unitType = 4;
	    			break;
	    		case 'workshop': $unitType = 5;
	    			break;
	    		case 'rallypoint': $unitType = 6;
	    			break;
	    		case 'armoryshop':  
	    		case 'weaponshop': 
				case 'luxoryshop': 
				case 'guild':  
	    		case 'castle': 
	    		case 'wall': 
	    		default: 
	    			$unitType = -1;
	    		break;
    	  }
    	  
    	  return $unitType;
    }

    private function getUserBuildingDetails($currentBuildingName, $user_id)
    {
    	 //get current building details   	
    	$buildingDetails = new stdClass();
	    $userBuildings = new Application_Model_UserBuildings(); 
	    $result = $userBuildings->getBuildingsDetails($currentBuildingName);
	    
		if($result != null) {
			//'id','name','building_story','type', 'building_identifier', 'initial_cost', 'cost_per_upgrade', 'max_building_lvl', 'building_restriction'+
			// 'building_identifier_restriction', 'restriction_level'
			$buildingDetails->buildingText = ucfirst($currentBuildingName) .' is a '. $result['type']. ' building. '; 	    
			$buildingDetails->buildingText = $buildingDetails->buildingText.$result['building_story'];

			$buildingDetails->buildingType = $result['type'];
			$buildingDetails->buildingId = $result['id'];
			$buildingDetails->buildingIdentif = $result['building_identifier'];
			$buildingDetails->buildingInitCost = $result['initial_cost'];
			$buildingDetails->buildingCostPerUpgr = $result['cost_per_upgrade'];
			$buildingDetails->buildingMaxLvl = $result['max_building_lvl'];
			$buildingDetails->buildingRestrictionIdentifier = $result['building_identifier_restriction'];
			$buildingDetails->buildingRestrictionIdentifierLevel = $result['restriction_level'];
			
			$buildingDetails->buildingName = $currentBuildingName;
			
			$buildingDetails->buildingLevel = $this->getBuildingLevel($user_id, $buildingDetails->buildingId);
			if( $buildingDetails->buildingLevel == 0 )
			{
				$buildingDetails->buildingUpgradeCost = $buildingDetails->buildingInitCost;
			}
			else 
			{
				$buildingDetails->buildingUpgradeCost =$buildingDetails->buildingInitCost + $buildingDetails->buildingLevel*$buildingDetails->buildingCostPerUpgr;
			}
			
			$playerStats = new Application_Model_PlayerStats();
			$result = $playerStats->getPlayerStats($user_id);
		  	if( strtolower($result['class_name']) == 'light' )
	    	{
	    		$buildingDetails->buildingUpgradeCost = $buildingDetails->buildingUpgradeCost - $buildingDetails->buildingUpgradeCost*0.10;
	    	}
		}	
		return $buildingDetails;
    }

    private function getBuildingLevel($user_id, $building_id)
    {
    	$userBuildings = new Application_Model_UserBuildings(); 
    	$result = $userBuildings->getBuildingCurrLevel($building_id, $user_id);
			//'user_fk','building_fk','building_current_lvl'
		if($result == null)
		{
			return 0;
		}
		else
		{
			return $result['building_current_lvl'];
		}
    	
    }

    private function getBuildingCapacity($buildingCost, $unitType, $powerLvl1, $buildingLevelAfterUpgrade, $user_id)
    {
    	if( $unitType == 1)
    		$capacity = round((250 * $buildingLevelAfterUpgrade)/$powerLvl1); 
    	else if($unitType >=2 && $unitType <=6)
    	{
    		$capacity = round(($buildingCost/$powerLvl1 + $buildingCost/$powerLvl1 * 0.05)/200);
    	}  
    	
    	$playerStats = new Application_Model_PlayerStats();
		$result = $playerStats->getPlayerStats($user_id);
		if( strtolower($result['class_name']) == 'dark' )
	    {
	    	$capacity = $capacity * 0.10 + $capacity;
	    }

    	return $capacity;
    }

    private function user_train($buildingName, $nrTrain, $user_id)
    {
    	$userStats = new Application_Model_UserStatsTbl();
    	
    	$this->setBuildingValues($user_id, $buildingName);
    	
		$unitType = $this->getUnitTypeFromBuildingName($buildingName);
		if($unitType == 1 || $unitType == 6 || $unitType == -1)
		{
			return 'Invalid Type of unit!';
		}
		else
		{
			//1. get number of level 1 units available for train
			$nrLvl1 = $this->_userArmy->lvl1;

			if( $nrLvl1 <  $nrTrain )
	   		{
	   			return 'You dont have enough lvl1 troops to procede training process!';
	   		}
	   		
	   		$unit = $this->getCurrentUnitSettings($unitType);
	   		$totalTrainCost = $nrTrain *  $unit->trainingCost;
	   		$totalPowerEarned = $nrTrain * $unit->trainingPower;
	    	
	   		
	    	if( $this->_currentUserStats->currentWealth < $totalTrainCost )
	    	{
	    		return 'Not enough coins to procede training process!';
	    	}

	    	$incomeEarn = $unit->trainingIncome * $nrTrain;
	    	
	    	if( $this->_currentUserStats->raceId == 1 )
	    	{
	    		$racialBonus = 0;
	    		$incomeEarn = $incomeEarn * $racialBonus + $incomeEarn;
	    	}
		    
	    	//2. update wealth,power, income
			$row = $userStats->fetchRow($userStats->select()->where('user_fk = ?', $user_id));
			$row->wealth = $row->wealth - $totalTrainCost;
			$row->power  = $row->power + $totalPowerEarned;
			$row->income = $row->income +  $incomeEarn;
    		$row->save();
    		
    		//3. update troops table
    		//$columnName = 'lvl'. $unitType;
			if( $this->_currentUserStats->classFK == 1 )
	   		{
	    		$lighArmy = new Application_Model_LightUserArmyTbl();
	    		$row = $lighArmy->fetchRow($lighArmy->select()->where('user_fk = ?', $user_id));	    		
	    	}
	    	else 
	   		{
	   			$darkArmy = new Application_Model_DarkUserArmyTbl();	
	   			$row = $darkArmy->fetchRow($darkArmy->select()->where('user_fk = ?', $user_id));
	   		}
	   		
	   		$row->lvl1 = $row->lvl1 - $nrTrain;
	    		
    		switch ($unitType) {
    			case 2:
    			$row->lvl2 += $nrTrain;
    			break;
    			
    			case 3:
    			$row->lvl3 += $nrTrain;
    			break;
    			
    			case 4:
    			$row->lvl4 += $nrTrain;
    			break;
    			
    			case 5:
    			$row->lvl5 += $nrTrain;
    			break;
    			
    			default:
    			break;
    		}
    		$row->save();
	   		
		}
		return 'ok';
    }

    private function user_hire($buildingName, $nrHire, $user_id)
    {
		$userStats = new Application_Model_UserStatsTbl();
    	
    	$this->setBuildingValues($user_id, $buildingName);
    	
		$unitType = $this->getUnitTypeFromBuildingName($buildingName);

		$unit = $this->getCurrentUnitSettings($unitType);
	   	$totalHireCost = $nrHire *  $unit->cost;
	   	$totalPowerEarned = $nrHire * $unit->power;
	    	
	   	if( $this->_currentUserStats->currentWealth < $totalHireCost )
	    {
	    	return 'Not enough coins to procede training process!';
	    }
	    
	    	
	    
    	$incomeEarn = $unit->income * $nrHire;
	    if( $this->_currentUserStats->raceId == 1 )
	    {
	    	$racialBonus = 0;
	    	$incomeEarn = $incomeEarn * $racialBonus + $incomeEarn;
	    }
		    
	    //2. update wealth,power, income, current population
		$row = $userStats->fetchRow($userStats->select()->where('user_fk = ?', $user_id));
		$row->wealth = $row->wealth - $totalHireCost;
		$row->power  = $row->power + $totalPowerEarned;
		$row->income = $row->income +  $incomeEarn;
		$row->current_population  += $nrHire; 
		
		if ( $row->current_population > $row->total_population )
		{
			$populationNeeded = $row->current_population - $row->total_population;
			$message = 'You need to get more space for the hire process('. $populationNeeded . ')';
			return $message; 
		}
		
    	$row->save();
    		
    	//3. update troops table
    	//$columnName = 'lvl'. $unitType;
		if( $this->_currentUserStats->classFK == 1 )
	   	{
	    	$lighArmy = new Application_Model_LightUserArmyTbl();
	    	$row = $lighArmy->fetchRow($lighArmy->select()->where('user_fk = ?', $user_id));	    		
	    }
	    else 
	   	{
	   		$darkArmy = new Application_Model_DarkUserArmyTbl();	
	   		$row = $darkArmy->fetchRow($darkArmy->select()->where('user_fk = ?', $user_id));
	   	}
	   			    		
    	switch ($unitType) {
    		case 1:
    		$row->lvl1 += $nrHire;
    		break;
    		case 2:
    		$row->lvl2 += $nrHire;
    		break;
    			
    		case 3:
    		$row->lvl3 += $nrHire;
    		break;
    			
    		case 4:
    		$row->lvl4 += $nrHire;
    		break;
    			
    		case 5:
    		$row->lvl5 += $nrHire;
    		break;
    		
    		case 6:
    		$row->lvl6 += $nrHire;
    		break;
    			
    		default:
    		break;
    	}
    	$row->save();
    	
		return 'ok';
    }

    
public function buildAction()
    {
		$buildingUpgrade = new Application_Form_Building();
    	$buildingName = $_POST['buildingUpgradeName'];
    	
     	if( $_GET['v'] != null){
   			$buildingName = $_GET['v'];
    	}
    	
    	if ( $buildingName == null )
    	{
    		$this->_redirect('kingdom/list');
    	}
    	
    	$auth = Zend_Auth::getInstance();
       	if ($auth->hasIdentity()) 
        {
            $user_id = $auth->getIdentity()->id; 
        }
        else 
        {
        	$this->_redirect('authentication/login');
        }
        
        $this->view->buildingName = $buildingName;
       	$buildingUpgrade->buildingUpgradeName->setValue($buildingName);
       	$this->setBuildingValues($user_id, $buildingName);
    	
    	
    	//apply restrictions for buildings
	    $restrictionBuildingName = 0;
	    $restrictionBuildingLevel =  0;
	    $upgradeCost = $this->_userBuildingDetails->buildingUpgradeCost;
	    $story = $this->_userBuildingDetails->buildingText;
	    $currentBuildingLevel = $this->_userBuildingDetails->buildingLevel;
	 
	    if( $this->_restrictions->building->buildingRestrictionName != "0" || $this->_restrictions->building->buildingCostRestriction != 0 )
	    {
	    	//disable BUILD BUTTON
	    	$buildingUpgrade->build->setAttrib('disabled', 'disabled');
	    	$restrictionBuildingName = $this->_restrictions->building->buildingRestrictionName;
	    	$restrictionBuildingLevel =  $this->_restrictions->building->buildingRestrictionLevel;
	    }
	    
	    $restrictionBuildingMax = 0;
	    if($currentBuildingLevel == $this->_userBuildingDetails->buildingMaxLvl ) 
	    {
	    	//disable BUILD BUTTON
	    	$buildingUpgrade->build->setAttrib('disabled', 'disabled');
	    	$restrictionBuildingMax  = 'You reach the maximum level of the ' .ucfirst($buildingName). ' building!<br/> No more upgrades requered! ';
	    }
	    
	    //set variables to the view
	    $unitType = $this->getUnitTypeFromBuildingName($buildingName);
	    $this->view->level = $unitType;
	    $this->view->buildingUpgrade = $buildingUpgrade; //form with button of BUILD
	    
	    $this->view->buildingUpgradeCost = $upgradeCost;
	    $this->view->buildingRestrict = $restrictionBuildingName;
		$this->view->buildingRestrictLvl = $restrictionBuildingLevel;
		$this->view->buildingText = $story;
		$this->view->buildingLevel = $currentBuildingLevel;
		$this->view->buildingRestrictionMaxLevel = $restrictionBuildingMax;
		
    	$url = 'buildings/build'.'?v='.$buildingName;
        
    	if($this->getRequest()->isPost())
	    {
	    	if($buildingUpgrade->isValid($_POST))
	    	{
	    		//call user_uprade building
	    		$result = $this->user_build($buildingName, $user_id);
	    		$this->_redirect($url);
	      	}
	      	$this->_redirect($url);
	    
    	}
    }

    public function trainAction()
    {
    	$buildingTrain = new Application_Form_TrainUnits();
    	$buildingName = $_POST['buildingTrainingName'];
    	$url = 'buildings/actions'.'?v='.$buildingName;
    	
	    $redirector = $this->_helper->getHelper('Redirector');
    	$auth = Zend_Auth::getInstance();
       	if ($auth->hasIdentity()) 
        {
            $user_id = $auth->getIdentity()->id; 
        }
        else 
        {
        	$this->_redirect('authentication/login');
        }
    	
    	if($this->getRequest()->isPost())
	    {
	    	
	    	if($buildingTrain->isValid($_POST))
	    	{
	    		//call user_training : unitsNrTrain
	    		$unitType = $this->getUnitTypeFromBuildingName($buildingName);
	    		$nrTrain = $buildingTrain->getValue('unitsNrTrain');
	    		$nrTrain = abs($nrTrain);
	    		$result = $this->user_train($buildingName, $nrTrain, $user_id);
	    		if($result == 'ok')
	    			$this->_redirect($url);
	    		else 
	    			$redirector->gotoSimple('units',
                                       'buildings',
                                       null,
                                       array('buildingName' => $buildingName,
                                             'errorHire' => $result));
	        }
	        else 
	        {
				$codes = $buildingTrain->getErrors('unitsNrTrain');
    			$messages = $buildingTrain->getMessages('unitsNrTrain');
				$redirector->gotoSimple('units',
                                       'buildings',
                                       null,
                                       array('buildingName' => $buildingName,
                                             'errorTrain' => $messages)
                                       );
                                       
    		}
	        
	        $this->_redirect($url);
	    }
    	
    }

    public function hireAction()
    {
    	$buildingHire = new Application_Form_HireUnits();
    	$buildingName = $_POST['buildingHireName'];
    	$url = 'buildings/actions'.'?v='.$buildingName;
    	
    	$redirector = $this->_helper->getHelper('Redirector');
    	
    	$auth = Zend_Auth::getInstance();
       	if ($auth->hasIdentity()) 
        {
            $user_id = $auth->getIdentity()->id; 
        }
        else 
        {
        	$this->_redirect('authentication/login');
        }
        
    	if($this->getRequest()->isPost())
	    {
			if($buildingHire->isValid($_POST))
	    	{
	    		//call user_hire : unitsNrHire
	    		$unitType = $this->getUnitTypeFromBuildingName($buildingName);
	    		$nrHire = $buildingHire->getValue('unitsNrHire');
	    		$nrHire = abs($nrHire);
	    		$result = $this->user_hire($buildingName, $nrHire, $user_id);
	    		if($result == 'ok')
	    			$this->_redirect($url);
	    		else 
	    		{
	    			$redirector->gotoSimple('units',
                                       'buildings',
                                       null,
                                       array('buildingName' => $buildingName,
                                             'errorHire' => $result));
	    		}
	    		
	        }
	    	else 
	        {
				$codes = $buildingHire->getErrors('unitsNrHire');
    			$messages = $buildingHire->getMessages('unitsNrHire');
				$redirector->gotoSimple('units',
                                       'buildings',
                                       null,
                                       array('buildingName' => $buildingName,
                                             'errorHire' => $messages)
                                       );
                                       
    		}
	        $this->_redirect($url);
	    
		
    	}
    }

    public function unitsAction()
    {
	  	$currUrl = $this->getRequest()->getRequestUri();
  		list($firstSlash, $controllerName, $actionName, $buildingNameTag, $buildingNameUrl, $errorTag, $error) = explode('/', $currUrl);
    	
        if( $_GET['v'] != null){
    		$buildingName = $_GET['v'];
    	}
    	else 
    	{
	    	if ($buildingNameUrl != null)
    		{
    			$buildingName = $buildingNameUrl;
    		}
    	}
    	
    	if ( $buildingName == null )
    	{
    		$this->_redirect('kingdom/list');
    	}
    	
    	$auth = Zend_Auth::getInstance();
       	if ($auth->hasIdentity()) 
        {
            $user_id = $auth->getIdentity()->id; 
            $unitType = $this->getUnitTypeFromBuildingName($buildingName);         
        }
        else 
        {
        	$this->_redirect('authentication/login');
        }
        
       	$this->setBuildingValues($user_id, $buildingName);
        $this->view->buildingName = $buildingName;
        
       	$buildingTrain = new Application_Form_TrainUnits();
		$buildingHire = new Application_Form_HireUnits();
	    
		$buildingTrain->buildingTrainingName->setValue($buildingName);
		$buildingHire->buildingHireName->setValue($buildingName);

		$unit = $this->getCurrentUnitSettings($unitType);
		 
		//1. apply restrictions for training
		$restrictionBuildingName = 0;
	    $restrictionBuildingLevel =  0;
	    $restrictionBuildingPopulation = 0;
	    $trainCost = $unit->trainingCost;
	    $trainPower = $unit->trainingPower;
	    $this->view->lvl1Untrained = $this->_userArmy->lvl1;
	    $story = $unit->name .' will take a level 1 unit and it will be trained to level '. $unitType. ' unit.'. $unit->story;
		
	    $this->view->level = $unitType;
	    
	  	if( $this->_restrictions->training->buildingName != "0" ) 
	    {
	    	//disable BUILD BUTTON
	    	$buildingTrain->train->setAttrib('disabled', 'disabled');
	    	$restrictionBuildingName =  $this->_restrictions->training->buildingName;
	    	$restrictionBuildingLevel =  $this->_restrictions->training->buildingLevel;
	    }
	    
	    if($this->_restrictions->training->population != "0" )
	    {
	    	$restrictionBuildingPopulation = $this->_restrictions->training->population;
	    }
	    
	    //set variables to the view
    	if ( $this->_restrictions->training->farms == "0" )
	    {
	    	$this->view->buildingTrain = $buildingTrain; //form with button of TRAIN
		    $this->view->trainRestrict = $restrictionBuildingName;
			$this->view->trainRestrictLvl = $restrictionBuildingLevel;
			$this->view->trainRestrictPopulation = $restrictionBuildingPopulation;
			$this->view->trainCost = $trainCost;
			$this->view->trainPower = $trainPower;
			$this->view->trainStory = $story;
	    }
	    else {
	    	 $this->view->trainRestrict = $this->_restrictions->training->farms;
	    	 $this->view->trainRestrictLvl = -1;
	    	 $this->view->trainRestrictPopulation = 0;
	    }
	    
	    if( $errorTag == 'errorTrain')
	    {
	    	$error = $this->fixString($error);
	    	$buildingTrain->errorTrainLabel->setLabel($error);
	    }
	    
		
		
		//2. apply restriction for hire
		$restrictionBuildingName = 0;
	    $restrictionBuildingLevel =  0;
	    $restrictionBuildingPopulation = 0;
	    $hireCost = $unit->cost;
	    $hirePower = $unit->power;
	    $story = $unit->name;
	    
		if( $this->_restrictions->hire->buildingName != "0" ) 
	    {
	    	//disable BUILD BUTTON
	    	$buildingHire->hire->setAttrib('disabled', 'disabled');
	    	$restrictionBuildingName = $this->_restrictions->hire->buildingName;
	    	$restrictionBuildingLevel = $this->_restrictions->hire->buildingLevel;
	    }
	   	if( $this->_restrictions->hire->population != "0" )
	   	{
    		$restrictionBuildingPopulation = $this->_restrictions->hire->population;
	   	}
	    
	    
	    //set variables to the view
	   	$this->view->buildingHire = $buildingHire; //form with button of TRAIN
	    $this->view->hireRestrict = $restrictionBuildingName;
		$this->view->hireRestrictLvl = $restrictionBuildingLevel;
		$this->view->hireRestrictPopulation = $restrictionBuildingPopulation;
		$this->view->hireCost = $hireCost;
		$this->view->hirePower = $hirePower;
		$this->view->hireStory = $story;
		$this->view->hireSpaceAvailable = $this->_currentUserStats->total_population - $this->_currentUserStats->current_population; 
		
     	if( $errorTag == 'errorHire')
	    {
	    	$error = $this->fixString($error);
	    	$buildingHire->errorHireLabel->setLabel($error);
	    }
    	
    }
    


}














